<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>
				</div><div class="flex-end-center-wrap">
					<div class="flex-end-center-wrap">
						<el-checkbox v-model="quickSearch">快捷筛选</el-checkbox>
						<el-radio-group v-if="quickSearch" v-model="searchParams.period" size="small" style="margin: 0 5px" @change="onStateChange">
							<el-radio-button label="1">本天</el-radio-button>
							<el-radio-button label="2">本周</el-radio-button>
							<el-radio-button label="3">本月</el-radio-button>
						</el-radio-group>
						<jk-date-picker v-else v-model="searchParams.belongDate" :disabled-future-time="true" size="small" type="daterange" style="width: 280px; margin: 0 5px" value-format="yyyy-MM-dd" placeholder="选择日期" class="search-bar-item-size1 item-gap"></jk-date-picker>
						<jk-select v-model="searchParams.auditState" :option-list="auditStateList" placeholder="状态" clearable class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
						<el-select v-model="searchParams.typeCode" placeholder="检验类型" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange">
							<el-option
								v-for="item in examineList"
								:key="item.code"
								:label="item.name"
								:value="item.code"
							>
							</el-option>
						</el-select>
						<jk-search-button @click="onSearchBtn"></jk-search-button>
					</div>

				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<jk-table
				ref="jkTable"
				:span-method="mergeRowMethod"
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 20"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-common-status v-if="item.keyName === 'auditState'" :status="scope.row.auditState"></jk-common-status>
						<span v-else-if="item.keyName === 'ifBase'">{{ scope.row.ifBase ? '是' : '否' }}</span>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="250">
					<template slot-scope="scope">
						<jk-operation-bar
							:scope="scope"
							api-prefix="spin/quality-inspection-record"
							:permission-prefix="prefix"
							@on-detail="onDetailBtn"
							@on-delete="onDeleteBtn"
							@on-edit="onEditBtn"
							@on-refresh="getListRequest"
						></jk-operation-bar>
					</template>
				</vxe-column>
			</jk-table>
			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<detail-dialog
			:data-id="dataId"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChangeOfDetailDialog"
		></detail-dialog>
		<save-dialog
			:permission-prefix="prefix"
			:data-id="dataId"
			:type-code="searchParams.typeCode"
			:type-id="searchParams.typeId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import { auditStateList } from '@/utils/jk/status-option-list';
    import saveDialog from './save-dialog';
    import detailDialog from './detail-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import {
        spinQualityInspectionRecordDelete, spinQualityInspectionRecordExportExcel,
        spinQualityInspectionRecordPage
    } from '../../../api/quality/qualityRecord';
    import { systemBusinessDictPage } from '../../../api/quality/processQuality';
    import { pageConfig, formatMonth, formatDate, tipsBar } from '/src/utils/jk/jk-tool';
    import { spinQualityInspectionRecordMonthData } from '../../../api/quality/qualityDayReportForms';
    export default {
        name: 'WorkshopArea',
        components: {
            saveDialog,
            detailDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                prefix: 'spin:qualityInspectionRecord',
                apiItem: {
                    'page': spinQualityInspectionRecordPage,
                    'exportExcel': spinQualityInspectionRecordExportExcel,
                    'delete': spinQualityInspectionRecordDelete
                },
                examineList: [],
                importDialogState: false,
                auditStateList: auditStateList,
                detailDialogState: false,
                quickSearch: false,
                dataId: null,
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                searchParams: {
                    yearMonth: '',
                    typeCode: '',
                    typeId: '',
                    count: null,
                    productNameOrCode: '',
                    beginDate: '',
                    endDate: '',
                    radioTime: '',
                    period: 1
                }
            };
        },
        methods: {
            mergeRowMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['productName'];
                const cellValue = row[column.field];
                if (cellValue && fields.includes(column.field)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.field] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.field] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onWorkshopChange(e) {
                this.examineList.forEach(x => {
                    if (e === x.id) {
                        this.$set(this.searchParams, 'typeName', x.name);
                        this.$set(this.searchParams, 'typeCode', x.code);
                        this.$set(this.searchParams, 'typeId', x.id);
                    }
                });
                this.getListRequest();
            },
            getTypeListRequest() {
                const params = {
                    categoryCode: 'QUALITY_TYPE',
                    pageSize: 100,
                    pageNo: 1
                };
                return systemBusinessDictPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.examineList = res.data.res || [];
                        if (!this.searchParams.typeCode) {
                            this.$set(this.searchParams, 'typeName', res.data.res[0].name);
                            this.$set(this.searchParams, 'typeCode', res.data.res[0].code);
                            this.$set(this.searchParams, 'typeId', res.data.res[0].id);
                        }
                    }
                });
            },
            onVisibleChangeOfImportDialog(e) {
                this.importDialogState = e;
            },
            onFinishBtnOfImportDialog() {
                this.importDialogState = false;
                this.getListRequest();
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },

            onDeleteBtn(id) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    spinQualityInspectionRecordDelete({ id: id }).then(res => {
                        if (res.data.status === 200) {
                            this.$message({
                                type: 'success',
                                message: res.data.message ? res.data.message : '删除成功'
                            });
                            this.getListRequest();
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            onDetailBtn(e) {
                this.dataId = e.id;
                this.detailDialogState = true;
            },
            onVisibleChangeOfDetailDialog(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.detailDialogState = e;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.saveDialogState = e;
            },
            getDataParams() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                if (params.yearMonth) {
                    const date = new Date(params.yearMonth);
                    params.year = date.getFullYear();
                    params.month = date.getMonth() + 1;
                }
                const now = new Date();
                params.period = Number(params.period);
                if (this.quickSearch) {
                    // 处理时间范围
                    const now = new Date();
                    params.period = Number(params.period);
                    if (this.quickSearch) {
                        const getDateRange = (period) => {
                            switch (period) {
                            case 1: // 本天
                                return [formatDate(now), formatDate(now)];
                            case 2: // 本周
                                // eslint-disable-next-line no-case-declarations
                                const startOfWeek = new Date(now);
                                startOfWeek.setDate(now.getDate() - now.getDay() + 1);
                                return [formatDate(startOfWeek), formatDate(new Date())];
                            case 3: // 本月
                                // eslint-disable-next-line no-case-declarations
                                const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
                                return [formatDate(startOfMonth), formatDate(new Date())];
                            default:
                                return [];
                            }
                        };
                        params.radioTime = getDateRange(params.period);
                        params.beginDate = params.radioTime[0];
                        params.endDate = params.radioTime[1];
                        params.belongDate = [params.radioTime[0], params.radioTime[1]];
                    }

                    // 根据 quickSearch 删除不同的属性
                    if (this.quickSearch) {
                        delete params.year;
                        delete params.month;
                    } else {
                        delete params.beginDate;
                        delete params.endDate;
                    }
                }
                delete params.typeName;
                delete params.typeId;
                delete params.period;
                delete params.radioTime;

                return params;
            },
            onStateChange() {
                this.getListRequest();
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                this.tableData = [];
                this.apiItem.page(this.getDataParams()).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res ? res.data.res : [];
                        this.searchParams.count = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.saveDialogState = true;
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            async getDependentData() {
                this.$set(this.searchParams, 'yearMonth', formatMonth(Date.now()));
                await this.getTypeListRequest();
                await this.getMenuColumnListRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
